package com.atguigu.gmall.realtime.app.dim;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.app.func.DimSinkFunction;
import com.atguigu.gmall.realtime.app.func.TableProcessFunction;
import com.atguigu.gmall.realtime.beans.TableProcess;
import com.atguigu.gmall.realtime.common.GmallConfig;
import com.atguigu.gmall.realtime.utils.HbaseUtil;
import com.atguigu.gmall.realtime.utils.KafkaUtil;
import com.ververica.cdc.connectors.mysql.source.MySqlSource;
import com.ververica.cdc.connectors.mysql.table.StartupOptions;
import com.ververica.cdc.debezium.JsonDebeziumDeserializationSchema;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.restartstrategy.RestartStrategies;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.connector.kafka.source.KafkaSource;
import org.apache.flink.runtime.state.hashmap.HashMapStateBackend;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.datastream.BroadcastConnectedStream;
import org.apache.flink.streaming.api.datastream.BroadcastStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.CheckpointConfig;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.streaming.api.functions.co.BroadcastProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.hadoop.hbase.client.Connection;

import java.util.Properties;

/**
 * Created by 黄凯 on 2023/7/4 0004 16:47
 *
 * @author 黄凯
 * 永远相信美好的事情总会发生.
 * <p>
 * Dim层维度处理类
 * * 需要启动的进程
 * *      zk、kafka、maxwell、hdfs、hbase、DimApp
 *
 * 开发流程
 *  *      基本环境准备
 *  *      检查点相关设置
 *  *      从kafka主题中读取数据
 *  *      对流中数据类型进行转换并进行简单的ETL清洗     jsonStr->jsonObj
 *  *      ~~~~~~~~~~~~~~~~~~~~~~~~~~~主流~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 *  *      使用FlinkCDC到配置表中读取配置信息
 *  *      将读取到的配置信息封装为TableProcess对象
 *  *      根据配置信息提前在Habse中建表
 *  *      ~~~~~~~~~~~~~~~~~~~~~~~~~~~配置流~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 *  *      将配置流进行广播---broadcast(广播状态描述器)
 *  *      将主流和广播流进行关联---connect
 *  *      对关联之后的数据进行处理---process
 *  *      class TableProcessFunction extends BroadcastProcessFunction{
 *  *          open: 将配置信息预加载到configMap中
 *  *          processElement:处理主流业务数据
 *  *              获取广播状态
 *  *              获取处理的业务数据库表的名称
 *  *              根据表名到广播状态以及configMap中获取对应的配置信息
 *  *              如果能够获取的到，说明是维度数据，写到下游
 *  *                  过滤掉不需要传递的属性
 *  *                  补充type操作类型
 *  *                  补充配置信息
 *  *          processBroadcastElement:处理广播流配置数据
 *  *              op='d':从广播状态以及configMap中，将对应的配置信息删除掉
 *  *              op!='d':将对象的配置信息放到广播状态以及configMap中
 *  *
 *  *      }
 *  *      将流中的维度数据写到Hbase表中
 *  *          class DimSinkFunction extends RichSinkFunction{
 *  *              invoke{
 *  *                  type="delete"
 *  *                      从Hbase表中将数据删除
 *  *                  type!="delete"
 *  *                      将数据put到Hbase表中
 *  *              }
 *  *          }
 *  * 执行流程(以向业务数据库品牌表中添加xy品牌为例)
 *  *      当DimApp程序启动的时候，会将配置表中的配置信息加载到configMap以及广播状态中
 *  *      当向品牌表中添加一条数据后
 *  *      binlog会记录品牌表的变化
 *  *      maxwell从binlog获取变化数据,并将变化数据封装为json格式字符串发送到kafka的topic_db主题中
 *  *      DimApp从topic_db主题中读取数据
 *  *      根据广播状态中以及configMap中的配置信息判断当前处理的数据是不是维度
 *  *      如果是维度的话，发送到下游，输出到Hbase
 */
public class DimApp {

    public static void main(String[] args) throws Exception {

        //TODO 1.基本环境准备
        //1.1 指定流处理环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //1.2 设置并行度
        env.setParallelism(4);

        //TODO 2. 检查点相关的设置
        //2.1 开启检查点
        env.enableCheckpointing(5000L, CheckpointingMode.EXACTLY_ONCE);

        //2.2 设置检查点超时时间
        env.getCheckpointConfig().setCheckpointTimeout(60000L);

        //2.3 设置job取消之后检查点是否保留
        env.getCheckpointConfig().setExternalizedCheckpointCleanup(CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION);

        //2.4 设置两个检查点之间最小的时间间隔
        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(3000L);

        //2.5 设置重启策略

        //这种设置方法的意思是：只有3次重启机会，每隔3秒重启
        //如果7月5号重启2次，10月5号重启1次，那么3次机会用完了，到11月5号再错就不会重启了
        //3秒指的是，重启一次没成功，那么会等3秒再试着重启
//        env.setRestartStrategy(RestartStrategies.fixedDelayRestart(3,3000L));

        //这种设置方法的意思是：每30天有3次重启机会
        //到30天会归零，如果还有1次机会，那么30天之后，会重置成3次机会
        //后面那个3秒是重启间隔
        env.setRestartStrategy(RestartStrategies.failureRateRestart(3, Time.days(30), Time.seconds(3)));

        //2.6 设置状态后端
        env.setStateBackend(new HashMapStateBackend());
        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall/ck");

        //2.7 设置操作hadoop的用户
        System.setProperty("HADOOP_USER_NAME", "atguigu");

        //TODO 3.从kafka主题中读取数据
        //3.1 声明消费的主题以及消费者组
        String topic = "topic_db";
        String groupId = "dim_app_group";

        //3.2 创建消费者对象
        KafkaSource<String> kafkaSource = KafkaUtil.getKafkaSource(topic, groupId);

        //3.3 消费数据 封装为流
        DataStreamSource<String> kafkaStrDS = env.fromSource(kafkaSource, WatermarkStrategy.noWatermarks(), "Kafka Source");

        //TODO 4.对流中数据进行类型转换 jsonStr->jsonObj    并进行简单的ETL
        SingleOutputStreamOperator<JSONObject> jsonObjDS = kafkaStrDS.process(

                new ProcessFunction<String, JSONObject>() {
                    @Override
                    public void processElement(String jsonStr,
                                               ProcessFunction<String, JSONObject>.Context context,
                                               Collector<JSONObject> collector) {

                        JSONObject jsonObject = JSON.parseObject(jsonStr);

                        String type = jsonObject.getString("type");

                        if (!"bootstrap-start".equals(type) && !"bootstrap-complete".equals(type)) {

                            collector.collect(jsonObject);

                        }

                    }
                }

        );

//        jsonObjDS.print("666");

        //TODO 5.使用FlinkCDC读取配置表数据
        //5.1 创建MySqlSource
        Properties properties = new Properties();
        properties.setProperty("useSSL", "false");

        /**
         * >>>:3> {"before":null,"after":{"source_table":"financial_sku_cost","sink_table":"dim_financial_sku_cost",
         * "sink_family":"info","sink_columns":"id,sku_id,sku_name,busi_date,is_lastest,sku_cost,create_time","sink_row_key":"id"},
         * "source":{"version":"1.6.4.Final","connector":"mysql","name":"mysql_binlog_source","ts_ms":0,"snapshot":"false","db":"gmall0201_config",
         * "sequence":null,"table":"table_process_dim",
         * "server_id":0,"gtid":null,"file":"","pos":0,"row":0,"thread":null,"query":null},"op":"r","ts_ms":1688468369423,"transaction":null}
         */
        MySqlSource<String> mySqlSource = MySqlSource.<String>builder()
                .hostname("hadoop102")
                .port(3306)
                .databaseList("gmall0201_config")
                .tableList("gmall0201_config.table_process_dim")
                .username("root")
                .password("000000")
                .jdbcProperties(properties)
                .serverTimeZone("Asia/Shanghai")
                .deserializer(new JsonDebeziumDeserializationSchema())
                .startupOptions(StartupOptions.initial()) //读取历史数据
                .build();

        //5.2 读取数据，封装为流
        DataStreamSource<String> mysqlDS
                = env.fromSource(mySqlSource, WatermarkStrategy.noWatermarks(), "mysql_source");
//         mysqlDS.print(">>>");

        //5.3 将流中的数据进行类型转换， jsonStr->配置实体类对象
        SingleOutputStreamOperator<TableProcess> tableProcessDS = mysqlDS.map(

                new MapFunction<String, TableProcess>() {
                    @Override
                    public TableProcess map(String jsonStr) throws Exception {

                        JSONObject jsonObj = JSON.parseObject(jsonStr);
                        String op = jsonObj.getString("op");
                        TableProcess tableProcess = null;
                        if ("d".equals(op)) {
                            tableProcess = jsonObj.getObject("before", TableProcess.class);
                        } else {
                            tableProcess = jsonObj.getObject("after", TableProcess.class);
                        }

                        tableProcess.setOp(op);
                        return tableProcess;

                    }
                }

        );

//        tableProcessDS.print(">>>");

        //TODO 6.根据配置表中的配置信息提前在Hbase中将维度表创建出来
        tableProcessDS = tableProcessDS.process(

                new ProcessFunction<TableProcess, TableProcess>() {

                    private Connection conn;

                    @Override
                    public void open(Configuration parameters) throws Exception {

                        conn = HbaseUtil.getConnection();

                    }

                    @Override
                    public void close() throws Exception {

                        HbaseUtil.closeConnection(conn);

                    }

                    @Override
                    public void processElement(TableProcess tableProcess,
                                               ProcessFunction<TableProcess, TableProcess>.Context context,
                                               Collector<TableProcess> collector) throws Exception {

                        //获取对配置表进行的操作类型
                        String op = tableProcess.getOp();
                        //获取表名
                        String sinkTable = tableProcess.getSinkTable();

                        //获取列族
                        String sinkFamily = tableProcess.getSinkFamily();

                        if ("r".equals(op) || "c".equals(op)) {

                            //建表
                            HbaseUtil.createTable(conn, GmallConfig.HBASE_NAMESPACE, sinkTable, sinkFamily.split(","));

                        } else if ("d".equals(op)) {

                            //删表
                            HbaseUtil.dropTable(conn, GmallConfig.HBASE_NAMESPACE, sinkTable);

                        } else {

                            //先删表
                            HbaseUtil.dropTable(conn, GmallConfig.HBASE_NAMESPACE, sinkTable);
                            //再建表
                            HbaseUtil.createTable(conn, GmallConfig.HBASE_NAMESPACE, sinkTable, sinkFamily.split(","));

                        }

                        collector.collect(tableProcess);

                    }
                }

        );

        //TODO 7.将配置流进行广播---广播流
        MapStateDescriptor<String, TableProcess> mapStateDescriptor
                = new MapStateDescriptor<>("mapStateDescriptor", String.class, TableProcess.class);

        BroadcastStream<TableProcess> broadcastDS = tableProcessDS.broadcast(mapStateDescriptor);


        //TODO 8.将主流和广播流进行关联---connect
        BroadcastConnectedStream<JSONObject, TableProcess> connectDS = jsonObjDS.connect(broadcastDS);


        //TODO 9.对关联之后的数据进行处理--得到维度数据
        SingleOutputStreamOperator<JSONObject> dimDS = connectDS.process(
                new TableProcessFunction(mapStateDescriptor)
        );


        //TODO 10.将维度数据写到Hbase表中
        dimDS.print(">>>>");

        dimDS.addSink(
                new DimSinkFunction()
        );

        env.execute();


    }

}
